// import { login, logout, getInfo } from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth';

import userApi from '@/api/user';

import { staticRoutes, allAsyncRoutes, anyRoute } from '@/router/routes'

import {cloneDeep} from 'lodash'

import router from '@/router';

 // 筛选路由的函数
 const filterRoutesHandler = (routes, routesName) => {
  // console.log('11111111',routes, routesName);
  let result = routes.filter(route => {
    if (route.children) {
      route.children = filterRoutesHandler(route.children, routesName); // 递归调用
    }
    return routesName.includes(route.name);
  });

  return result;
}

const initUserInfoData = () => ({
  avatar: '',
  name: '',
  buttons: [],
  roles: [],
  routes: []
});

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    userInfo: initUserInfoData(),
    // 用于存储用户路由信息的数据
    menuRoutes: []
  };
};

const state = getDefaultState();

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState());
  },
  SET_TOKEN: (state, token) => {
    state.token = token;
  },
  SET_NAME: (state, name) => {
    state.name = name;
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar;
  },
  SET_USER_INFO: (state, userInfo) => {
    state.userInfo = userInfo;
  }
};

const actions = {
  // user login
  async login({ commit }, data) {
    try {
      let result = await userApi.login(data);
      if (result.code === 20000) {
        // 将token存储到localStorage中
        setToken(result.data.token);
        commit('SET_TOKEN', result.data.token);
      } else {
        return Promise.reject(result.message);
      }
    } catch (error) {
      return Promise.reject(error);
    }
  },

  // get user info
  async getInfo({ commit,state }) {
    try {
      let result = await userApi.getInfo();
      // console.log(result);
      // 存储用户信息
      commit('SET_USER_INFO', result.data);
      //存储用户名
      commit('SET_NAME', result.data.name);
      // 存储用户头像
      commit('SET_AVATAR', result.data.avatar);
      
      const filterRoutes = filterRoutesHandler( cloneDeep(allAsyncRoutes), result.data.routes); // 筛选过后的路由
      // console.log("筛选出来的",filterRoutes);
      // ---------------------------------
      const allRoutes = staticRoutes.concat(filterRoutes, anyRoute); // 任意路由必须放在所有路由的最后面
      // 注意这里需要使用state存储
      state.menuRoutes = allRoutes

      // if (!(state.menuRoutes && state.menuRoutes.length > 0)) {
      //   router.addRoutes(allRoutes)
      // }
      router.addRoutes(allRoutes)

    } catch (error) {
      // console.log('失败', error);
      return Promise.reject(error);
    }
  },
  // 退出登录 
  async logout({ commit, state }) {
    try {
      await userApi.logOut();
      // 删除local中保存的token
      removeToken();
      // 清除store中的token和用户信息
      commit('SET_TOKEN', '');
      //存储用户名
      commit('SET_NAME', '');
      // 存储用户头像
      commit('SET_AVATAR', '');
      // 初始化用户信息
      this.userInfo = initUserInfoData();
    } catch (error) {
      // console.log('推出失败', error);
      return Promise.reject(error);
    }
  },

  //#region 
  // // user login
  // login({ commit }, userInfo) {
  //   const { username, password } = userInfo
  //   return new Promise((resolve, reject) => {
  //     login({ username: username.trim(), password: password }).then(response => {
  //       const { data } = response
  //       commit('SET_TOKEN', data.token)
  //       setToken(data.token)
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // // get user info
  // getInfo({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     getInfo(state.token).then(response => {
  //       const { data } = response

  //       if (!data) {
  //         return reject('Verification failed, please Login again.')
  //       }

  //       const { name, avatar } = data

  //       commit('SET_NAME', name)
  //       commit('SET_AVATAR', avatar)
  //       resolve(data)
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },

  // user logout
  // logout({ commit, state }) {
  //   return new Promise((resolve, reject) => {
  //     logout(state.token).then(() => {
  //       removeToken() // must remove  token  first
  //       resetRouter()
  //       commit('RESET_STATE')
  //       resolve()
  //     }).catch(error => {
  //       reject(error)
  //     })
  //   })
  // },
  //#endregion

  // remove token

  // resetToken({ commit }) {
  //   return new Promise(resolve => {
  //     removeToken(); // must remove  token  first
  //     commit('RESET_STATE');
  //     resolve();
  //   });
  // },

};

export default {
  namespaced: true,
  state,
  mutations,
  actions
};

